import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { Login, UpdateInfo } from "@/api/user";
import { IUserLoginParams } from "@/types/login";
import type { IUpdateUserInfo, IUser } from "@/types/user";
import { useSystem } from "./system";
import { useCache } from "./cache";
import { ElMessage } from "element-plus";

export const useUser = defineStore(
  "user",
  () => {
    const cache = useCache();
    const system = useSystem();
    const token = ref<string | null>(null);
    const userInfo = ref<IUser | null>(null);
    const isAuthenticated = computed(() => token.value);
    const userId = computed(() => userInfo.value?.id);
    const avatar = computed(() => userInfo.value?.avatar);
    const name = computed(() => userInfo.value?.name);
    const status = computed(() => userInfo.value?.status);

    // 设置用户信息
    function SetUserInfo(data: IUpdateUserInfo) {
      Object.assign(userInfo.value!, data);
    }

    // 登录
    async function UserLogin(data: IUserLoginParams) {
      try {
        const res = await Login(data);
        if (res?.status !== 200) throw new Error("登录失败，请检查账号密码");
        const { userToken, user, messages } = res.data;
        token.value = userToken;
        userInfo.value = user;
        await Promise.all([cache.GetUserFriendList(), cache.GetUserJoinGroup(), cache.GetUserFriendGroupList()]);
        await connectWebSocket(userToken, user.id, messages);
      } catch (error) {
        console.error("登录出错", error);
        ElMessage.error(error instanceof Error ? error.message : "登录出现错误");
      }
    }

    // 提取WebSocket连接逻辑
    async function connectWebSocket(token: string, userId: number, messages: any) {
      try {
        const wsRes = await window.electronApi.connectWs({
          token,
          id: userId,
          messages,
        });
        if (!wsRes) throw new Error("WebSocket 连接失败");
        const { defaultDownloadPath, dataBsePath } = wsRes;
        system.DefaultDownloadPath = system.DefaultDownloadPath || defaultDownloadPath;
        system.DateBasePath = dataBsePath;
      } catch (error) {
        console.error("WebSocket连接失败", error);
        throw new Error("无法建立实时连接，请检查网络");
      }
    }

    // 更新用户信息
    async function UpdateUserInfo(data: IUpdateUserInfo, callBack?: Function) {
      try {
        const res = await UpdateInfo(data);
        if (res.status !== 200) throw new Error("服务器响应失败");
        SetUserInfo(data);
        ElMessage.success("修改成功");
      } catch (err) {
        ElMessage.error(`修改失败: ${String(err)}`);
      } finally {
        if (callBack) callBack();
      }
    }

    // 重置
    function ResetUserState() {
      token.value = null;
      userInfo.value = null;
    }

    function ResetUser() {
      localStorage.removeItem("user");
    }

    return {
      token,
      userInfo,
      isAuthenticated,
      userId,
      avatar,
      name,
      status,
      SetUserInfo,
      UserLogin,
      UpdateUserInfo,
      ResetUser,
      ResetUserState,
    };
  },
  {
    share: {
      enable: true,
      initialize: true,
    },
    localStore: {
      store: true,
    },
  },
);
